package com.pdf.generate_pdf.service.impl;

import com.pdf.generate_pdf.common.PdfUtil;
import com.pdf.generate_pdf.entity.GeneratePdfEntity;
import com.pdf.generate_pdf.entity.SchoolReportEntity;
import com.pdf.generate_pdf.mapper.GeneratePdfMapper;
import com.pdf.generate_pdf.mapper.SchoolReportMapper;
import com.pdf.generate_pdf.service.GeneratePdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zzt
 * @date 2021/12/7
 */
@Service
public class GeneratePdfServiceImpl implements GeneratePdfService {

    @Autowired
    private GeneratePdfMapper generatePdfMapper;

    @Autowired
    private SchoolReportMapper schoolReportMapper;

    @Override
    public String addTemplateService(MultipartFile template) {
        byte[] templateBytes = new byte[0];
        GeneratePdfEntity entity = new GeneratePdfEntity();
        try {
            templateBytes = template.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!ObjectUtils.isEmpty(templateBytes)) {

            Long id = System.currentTimeMillis();
            entity.setId(id);
            entity.setTemplate(templateBytes);
        } else {
            return "获取模板错误!";
        }
        generatePdfMapper.addTemplateMapper(entity);
        return "保存成功!";
    }

    /**
     * 生成pdf
     * @param id
     * @return
     */
    @Override
    public String generatePdfService(String id) {
        GeneratePdfEntity entity = generatePdfMapper.queryTemplateByIdMapper(id);
        byte[] template = entity.getTemplate();
        String outPutPath = "D:\\" + System.currentTimeMillis() + ".pdf";
        List<SchoolReportEntity> list = schoolReportMapper.querySchoolreportList();
        Map<String, List<SchoolReportEntity>> data = new HashMap<>();
        data.put("data", list);
        PdfUtil.generatePdfByByteArrays(template,data,outPutPath);
        return "成功!";
    }
}
